package com.echo.yixiaowu.feature.components

import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import coil3.ImageLoader
import com.echo.yixiaowu.feature.main.home.RecommendState
import com.echo.yixiaowu.feature.main.home.HomeEvent
import com.echo.yixiaowu.feature.main.home.SortState
import com.echo.yixiaowu.main.CollapsedHeader
import com.echo.yixiaowu.route.AppRoute
import com.echo.yixiaowu.ui.theme.ContentColor

/**
 * 承载主内容区域，包含可折叠的Header和第一层级的HorizontalPager
 */
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun HomeContent(
    sortState: SortState,
    recommendState: RecommendState,
    onShowBottomSheet: () -> Unit,
    onEvent: (HomeEvent) -> Unit,
    sharedTransitionScope: SharedTransitionScope,
    animatedVisibilityScope: AnimatedVisibilityScope,
    imageLoader: ImageLoader,
    modifier: Modifier = Modifier,
    onNavigate: (AppRoute) -> Unit,
) {
    val density = LocalDensity.current
    val draggableItem = sortState.items
    val selectedIndex = draggableItem.indexOfFirst { it.isSelect }.coerceAtLeast(0)

    val homeTitlePagerState =
        rememberPagerState(initialPage = selectedIndex, pageCount = { draggableItem.size })
    val listStates = sortState.listStates
    val topInsetPx = WindowInsets.statusBars.getTop(density)

    // 定义Header的高度常量
    val mFirstMenuHeight = 60.dp
    val mSecondSearchHeight = 55.dp
    val mStickyHeaderHeight = 40.dp
    val initialHeaderHeight = mFirstMenuHeight + mSecondSearchHeight + mStickyHeaderHeight

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(ContentColor)
    ) {
        // 最高层级pager
        HorizontalPager(
            state = homeTitlePagerState,
            modifier = Modifier.fillMaxSize(),
            userScrollEnabled = false, // 由顶层Tab点击切换
            key = { page -> draggableItem[page].id }
        ) { page ->
            CategoryPage(
                pageData = draggableItem[page],
                recommendState = recommendState,
                listState = listStates[page],
                innerGridStateList = sortState.innerGridStates,
                initialHeaderHeight = initialHeaderHeight,
                mFirstMenuHeight = mFirstMenuHeight,
                mStickyHeaderHeight = mStickyHeaderHeight,
                onEvent = onEvent,
                sharedTransitionScope = sharedTransitionScope,
                animatedVisibilityScope = animatedVisibilityScope,
                imageLoader = imageLoader,
                pageId = draggableItem[page].id,
                onNavigate = onNavigate
            )
        }

        // Header背景高度和颜色
        val currentListState = listStates[homeTitlePagerState.currentPage]
        val headBackgroundHeight by remember(homeTitlePagerState.currentPage) {
            derivedStateOf {
                if (currentListState.firstVisibleItemIndex == 0) {
                    val scrollOffsetPx = currentListState.firstVisibleItemScrollOffset.toFloat()
                    val initialHeightPx = with(density) { mFirstMenuHeight.toPx() }
                    (initialHeightPx - scrollOffsetPx).coerceAtLeast(0f)
                        .let { with(density) { it.toDp() } }
                } else {
                    0.dp
                }
            }
        }
        // 透明可以看见底部内容
        val headerBackgroundColor = if (headBackgroundHeight > 0.dp) {
            Color.Transparent
        } else {
            colorResource(draggableItem[homeTitlePagerState.currentPage].background)
        }

        // 覆盖在顶部的可折叠Header
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(headBackgroundHeight + mSecondSearchHeight + mStickyHeaderHeight)
                .background(headerBackgroundColor)
        ) {
            val topPaddingModifier = if (topInsetPx > 0) {
                Modifier.statusBarsPadding()
            } else {
                Modifier.padding(top = 37.dp)
            }
            CollapsedHeader(
                modifier = Modifier.then(topPaddingModifier),
                sortState = sortState,
                listState = currentListState,
                pagerState = homeTitlePagerState,
                mInitFirstMenuHeight = mFirstMenuHeight,
                mInitSecondSearchHeight = mSecondSearchHeight,
                onClickMenu = onShowBottomSheet,
                onEvent = onEvent
            )
        }
    }
}
